package com.imodia.checkoo.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;

import com.hsq.commons.util.db.GenericIbatisDao;
import com.hsq.commons.util.db.SqlParam;
import com.hsq.commons.util.db.annotation.SqlSpace;
import com.imodia.checkoo.bean.CmsArticleCatalogueBean;
import com.imodia.checkoo.service.CmsArticleCatalogueService;


@Service("cmsArticleCatalogueService")
@SqlSpace(spaceName="cmsarticlecatalogue")
public class CmsArticleCatalogueServiceImpl extends GenericIbatisDao<CmsArticleCatalogueBean, Integer> implements CmsArticleCatalogueService {
	


	public void saveBatch(List<CmsArticleCatalogueBean> list,int articleId){
		SqlParam sql = new SqlParam();
		sql.andEqualTo("article_id", String.valueOf(articleId));
		super.delete(sql);
		
		for(CmsArticleCatalogueBean art : list ){
			if(art.getListOrder()!=null && art.getListOrder()==1){
				setOrder(art.getCatalogueId());
			}else{
				setOrder2(art.getCatalogueId());
			}
		}
//		for(CmsArticleCatalogueBean art : list ){
//			cmsArticleCatalogueDao.deleteLast(art.getArticleId());
//		}
		super.batchInsert(list);
	}
	
	
	private int setOrder(int catalogueId){
		String sql = "update cms_article_catalogue set list_order  = list_order+1 where  (end_date is null or end_date<date_format(now(),'%Y.%m.%d')) and  catalogue_id = "+catalogueId;
		return super.getSqlDao().update(sql);
	}
	
	private int setOrder2(int catalogueId){
		String sql = "update cms_article_catalogue set list_order  = list_order+1 where (end_date is null or end_date<date_format(now(),'%Y.%m.%d')) and list_order<>1 and catalogue_id = "+catalogueId;
		return super.getSqlDao().update(sql);
	}
	
//	public int deleteLast(int catalogueId){
//	String sql = "delete from cms_article_catalogue where catalogue_id = "+catalogueId +" and list_order>100";
//	return super.updateBySql(sql);
//}
}